# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.http.response import JsonResponse
from django.core.paginator import Paginator
from models import Book
import json
from django.core import serializers
from pip._vendor.requests.models import Response
# Create your views here.
@require_http_methods(["GET"])
def add_book(request):
    response = {}
    try:
        book = Book(book_name=request.GET.get('book_name'))
        book.save()
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception,e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)
@require_http_methods(["POST"]) 
def show_books(request): 
    response = {}
    try:
        pageNum = request.POST.get('pageNum')
        pageSize = request.POST.get('pageSize')#每页显示数据
        books = Book.objects.all()
        paginator = Paginator(books, pageSize)
        books = paginator.page(pageNum)     #页码
        response['total'] = paginator.count #总条数
        #page2.object_list
        #books = Book.objects.filter()
        response['list']  = json.loads(serializers.serialize("json", books))
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception,e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)
@require_http_methods(["POST"]) 
def del_books(request):
    response = {}
    try:
        id = request.POST.get('bookId')
        Book.objects.filter(id=id).delete()
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception,e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)
